from django.urls import path, reverse
from django.shortcuts import render,HttpResponse
from django.utils.safestring import mark_safe
from django.forms.models import modelformset_factory
from stark.service.v1 import StarkHandler, get_choice_text, get_manytomany, BootStrapModelForm, SearchOption,get_datetime_text
from web.models import CourseRecord,StudyRecord,ClassList


class CourseRecordModelForm(BootStrapModelForm):
    class Meta:
        model = CourseRecord
        fields = ['day_num', 'teacher']


class StudyRecordModelForm(BootStrapModelForm):
    class Meta:
        model = StudyRecord
        fields = ['record']


class CourseRecordHandler(StarkHandler):
    model_form_class = CourseRecordModelForm

    def display_attendance(self,obj=None,is_header=None,*args,**kwargs):
        if is_header:
            return '考勤'
        name="{}:{}".format(self.site.namespace,self.get_url_name('attendance'))
        attendance_url=reverse(name, kwargs={'course_record_id': obj.pk})
        tpl="<a target='_blank' href='{}'>考勤</a>".format(attendance_url)
        return mark_safe(tpl)

    def display_edit_del(self,obj=None,is_header=None,*args,**kwargs):
        if is_header:
            return '操作'
        class_id=kwargs.get('class_id')
        tpl="<a href='{}'>编辑</a> <a href='{}'>删除</a>".format(
            self.reverse_change_url(pk=obj.pk,class_id=class_id),
            self.reverse_del_url(pk=obj.pk,class_id=class_id)
        )
        return mark_safe(tpl)

    list_display = ['class_object', 'day_num', 'teacher',
                    get_datetime_text('时间', 'date'),display_attendance ]

    # def get_list_display(self):
    #     value = []
    #     if self.list_display:
    #         value.extend(self.list_display)
    #         value.append(self.display_edit_del)
    #     return value

    def get_urls(self):
        """
        :return:
        """
        patterns = [
            path('list/<int:class_id>/', self.wapper(self.list_view), name=self.get_list_url_name),
            path('add/<int:class_id>/', self.wapper(self.add_view), name=self.get_add_url_name),
            path('edit/<int:class_id>/<int:pk>/',self.wapper(self.change_view),name=self.get_edit_url_name),
            path('delete/<int:class_id>/<int:pk>/',self.wapper(self.delete_view),name=self.get_del_url_name),
            path('attendance/<int:course_record_id>/',self.wapper(self.attendance_view),
                 name=self.get_url_name('attendance')),
            ]
        patterns.extend(self.extra_urls())
        # print(patterns)
        return patterns

    def attendance_view(self,request,course_record_id,*args,**kwargs):
        study_record_object_list=StudyRecord.objects.filter(course_record_id=course_record_id)
        study_model_formset= modelformset_factory(StudyRecord,form=StudyRecordModelForm,extra=0)
        if request.method=='POST':
            formset=study_model_formset(queryset=study_record_object_list,data=request.POST)
            if formset.is_valid():
                formset.save()
            return render(request,'attendance.html',{'formset':formset})
        formset=study_model_formset(queryset=study_record_object_list)

        return render(request,'attendance.html',{'formset':formset})

    def get_query_set(self, request, *args, **kwargs):
        class_id = kwargs.get('class_id')
        return self.model_class.objects.filter(class_object_id=class_id)

    def save(self, request, form, is_update, *args, **kwargs):
        class_id = kwargs.get('class_id')
        if not is_update:
            form.instance.class_object_id=class_id
        form.save()

    def action_multi_init(self,request,*args,**kwargs):
        course_record_id_list=request.POST.getlist('pk')
        class_id=kwargs.get('class_id')
        class_object=ClassList.objects.filter(id=class_id).first()

        if not class_object:
            return HttpResponse("班级不存在")

        student_object_list=class_object.student_set.all()


        for course_record_id in course_record_id_list:
            # 判断上课记录是否合法
            course_object=CourseRecord.objects.filter(id=course_record_id,
                                                      class_object_id=class_id).first()
            if not course_object:
                continue

            # 判断上课记录的考勤记录是否已经存在
            study_record_exists=StudyRecord.objects.filter(course_record=course_object).exists()
            if study_record_exists:
                # study_students=study_record_exists.students
                # print(study_students,student_object_list)
                # study_record_exists_list=StudyRecord.objects.filter(course_record=course_object).all()
                # print(student_object_list)
                # print(study_record_exists_list)
                # for item in study_record_exists_list:
                #     if item.student not in student_object_list:

                continue

            study_record_object_list=[StudyRecord(student_id=stu.id,course_record=course_object)
                                     for stu in student_object_list]
            StudyRecord.objects.bulk_create(study_record_object_list,batch_size=50)
    action_multi_init.text='批量初始化考勤'

    action_list = [action_multi_init]

